import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../data/dio/api/bt_dio_network.dart';
import '../../../data/dio/api/bt_net_data_source.dart';
import '../../../data/models/bt_config_item.dart';
import '../../../data/store/bt_hive_logon_store.dart';
import '../../../part/bt_rc_im_engine.dart';
import '../../../utils/bt_tool_utils.dart';
import '../../utils/bt_constants.dart';

class BtBootRepository {
  final logger = Logger();
  final BtNetDataSource network = BtDioNetwork();

  Future<void> getAppConfig() async {
    // Obtain shared preferences.
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    var map = <String, dynamic>{};
    //map["ver"] =  '0';
    map["ver"] = prefs.getString(appConfigVersion) ?? '0';
    network.getAppConfig('false', map).then((appConfigResult) async {
      if (appConfigResult.isSuccess) {
        if ((appConfigResult.data?.ver ?? '').isNotEmpty) {
          await prefs.setString(appConfigVersion, appConfigResult.data?.ver ?? '');
        }
        for (BtConfigItem item in appConfigResult.data?.items ?? []) {
          if (item.name == 'glt') {
            await prefs.setString(googleTranslationKey, item.data);
          }
          if (item.name == 'rck') {
            await prefs.setString(rongCloudKey, item.data);
          }
        }
      }
    }).catchError((error) {
      // non-200 error goes here.
      switch (error.runtimeType) {
        case DioException:
          // Here's the sample to get the failed response error code and message
          final res = (error as DioException).response;
          logger.e('Got error : ${res?.statusCode} -> ${res?.statusMessage}');
          break;
        default:
          logger.e('Error occurred: $error');
          break;
      }
    });
  }

  Future<void> validToken(String token, Function(bool success, String msg) onResult) async {
    var map = <String, dynamic>{};
    map["token"] = token;

    network.validToken(map).then((result) async {
      if (!result.isSuccess) {
        BtHiveLogonStore().deleteData();
        BtRcImEngine().destroy();
        resetAppConfigVersion();
      }
      onResult(result.isSuccess, result.msg);
    }).catchError((error) {
      // non-200 error goes here.
      switch (error.runtimeType) {
        case DioException:
          // Here's the sample to get the failed response error code and message
          final res = (error as DioException).response;
          logger.e('Got error : ${res?.statusCode} -> ${res?.statusMessage}');
          break;
        default:
          logger.e('Error occurred: $error');
          break;
      }
    });
  }
}
